<?php


namespace app\api\controller;

use think\facade\Db;
use app\api\BaseController;
/**
 * Class AuthGroup 用户组操作类，
 * @package app\api\controller
 */
class AuthGroup extends BaseController
{
/**
用户组表，
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
    `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
    `title` char(100) NOT NULL DEFAULT '' COMMENT '用户组中文名称',
    `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '用户组状态',
    `rules` char(80) NOT NULL DEFAULT '' COMMENT '用户组拥有的规则id， 多个规则","隔开',
    PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8mb4;
 * */
    protected $table = 'think_auth_group';
    public function getAuthGroupList(){
        $data = request()->param();
        $page = (int)$data['page'];
        $limit = (int)$data['limit'];
        $result2 = [];
        $result2['submit_name'] = ['=',$data['submit_name']??''];
        $result2['submit_time'] =  ['between', [$data['date1'] ?? '',$data['date2'] ?? '']];
        $w = array();
        foreach($result2 as $k=>$v) {
            if(is_array($v[1])){
                $start_time = $v[1][0];
                $end_time = $v[1][1];
                if($start_time!=""&&$end_time!=""){
                    $w[] = "$k $v[0] '$start_time' AND '$end_time'";
                }
            }else{
                if($v[1]!==""){
                    $w[] = "$k $v[0] '$v[1]'";
                }
            }

        }
        $where = join(' and ', $w);
        $table_data = Db::table($this->table)
            ->filter(function ($data){
                $data['rules_msg'] = Db::table('think_auth_rule')->whereIn('id',$data['rules'])->column('title');
                $data['routes'] =  explode(",", $data['rules']);
                return $data;
            })
            ->page($page,$limit)
            ->where($where)
            ->select();
        $table_total = Db::table($this->table)
            ->where($where)
            ->count();
        echo json_encode([
            'status' => 200,
            'msg' => 'ok',
            'data' => $table_data,
            'total' => $table_total
        ]);
        exit;
    }
    public function getMenus(){
        return json(['status'=>200,'data'=>$this->getTree2()]);
    }
    protected function getTree2($f_id=0,$level=0){
        $zhi =  Db::table('think_auth_rule')->select()->toArray();
        static $arr =array();
        foreach($zhi as $key=>$value){
            if($value['f_id']==$f_id){
                $value['level']=$level;
                $arr[] =$value;
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $this->getTree2($value['id'],$level+1);
            }
        }
        return $arr;
    }
    //添加用户组
    public function addAuthGroupList(){
        $data = request()->param();
        unset($data['key']);
        $data['rules'] = implode(',',$data['routes']);
        unset($data['routes']);
        $res = Db::table('think_auth_group')->insert($data);
        if($res)
            success('添加角色','');
        else
            fail('添加角色','');
    }
    //修改用户组
    public function updateAuthGroupList(){
        $data = request()->param();
        unset($data['rules_msg']);
        $data['rules'] = implode(',',$data['routes']);
        unset($data['routes']);
        $res = Db::table('think_auth_group')
            ->where('id',$data['id'])
            ->update($data);
        if($res)
            success('编辑角色','');
        else
            fail('编辑角色','');

    }
    //删除用户组
    public function delAuthGroupRole(){
        $data = request()->param();
        if($data['id'] == 1){
         return json(['status'=>500,'msg'=>'当前用户组【默认为最高权限】不可删除']);
        }
        // 启动事务
        Db::startTrans();
        try {
            Db::table('think_auth_group')->where('id',$data['id'])->delete();
            Db::table('think_auth_group_access')->where('group_id',$data['id'])->delete();
            // 提交事务
            Db::commit();
            return json(['status'=>200,'msg'=>'删除成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>500,'msg'=>'删除失败']);
        }
    }
}